//
//  DeliveryViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-14.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "DeliveryViewController.h"
#import "DeliveryCell.h"
#import "DShopInfoViewController.h"
#import "DbManager.h"

#define DISTANCE @""
#define TITLE_WIDTH 140
#define TITLE_HEIGHT 200

@implementation DeliveryViewController

- (id)init
{
    self = [super initWithNibClass:[DeliveryViewController class]];
    if (self) {
        _selDistance = DISTANCE;
        _dataSource = [[DeliveryDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [_dataSource fetchDistance];
    [_dataSource fetchDeliverysWithDistance:_selDistance isLoadMore:NO];
    
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self createNavigation:@"附近外卖"];
    self.navigationItem.titleView = _titleButton;
    
    _selectDistanceView = [[SelDeliveryDistanceView alloc] initWithFrame:CGRectMake((ScreenWidth-TITLE_WIDTH)/2, -TITLE_HEIGHT, TITLE_WIDTH, TITLE_HEIGHT)];
    _selectDistanceView.delegate = self;
    [self.view addSubview:_selectDistanceView];
    
    _deliveryTable.delegate = _dataSource;
    _deliveryTable.dataSource = _dataSource;

    [_selectDistanceView loadDataWithArray:_dataSource.distanceList];
    
    NSDictionary *dic = _dataSource.distanceList[0];
    [_titleButton setTitleForNormal:[dic objectForKey:@"display"]];
}

- (IBAction)selectDistanceAction:(id)sender
{
    [_selectDistanceView showOrVisible];
}

- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.deliveryList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.deliveryList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [_deliveryTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    self.moreLoading = NO;
}

- (void)selectedDistanceFinished:(NSDictionary *)dic
{
    NSString *display = [dic objectForKey:@"display"];
    _selDistance = [dic objectForKey:@"juli"];
    [_titleButton setTitleForNormal:display];
    [_dataSource fetchDeliverysWithDistance:_selDistance isLoadMore:NO];
    [_selectDistanceView showOrVisible];
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation DeliveryDataSource

#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _deliveryList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    
    return self;
}

- (void)fetchDeliverysWithDistance:(NSString*)distance isLoadMore:(BOOL)isLoadMore
{
    if (!isLoadMore) [SVProgressHUD show];
    
    self.pageNumber = isLoadMore ? self.pageNumber : 1;
    
    NSString *url = [NSString stringWithFormat:API_HOME_DELIVERY,[AppSetting longitude],[AppSetting latitude],distance,self.pageNumber,[AppSetting cityId]];
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)fetchDistance
{
    _distanceList = [[DbManager sharedManager] fetchDistances];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == FETCH_NEW_TAG) {
        self.deliveryList = [json objectForKey:@"waimai"];
        [self.viewController.deliveryTable reloadData];
    }
    
    if (request.tag == FETCH_MORE_TAG) {
        [self.viewController appendTableWith:[json objectForKey:@"waimai"]];
    }
    
    [SVProgressHUD dismiss];
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _deliveryList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"DeliveryCell";
    DeliveryCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    
    NSDictionary *dictionary = [_deliveryList objectAtIndex:indexPath.row];
    [cell setContent:dictionary];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_deliveryList objectAtIndex:indexPath.row];
    NSString *shopId = [dic objectForKey:@"id"];
    
    DShopInfoViewController *shopInfoVC = [[DShopInfoViewController alloc] initWithId:shopId];
    [self.viewController.navigationController pushViewController:shopInfoVC animated:YES];
}

#pragma 分页加载
-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _deliveryList.count-1) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            [self fetchDeliverysWithDistance:_viewController.selDistance isLoadMore:YES];
            self.viewController.moreLoading = YES;
        }
    }
}

@end

#pragma=============================================================================
//======================下拉菜单=====================================================
#pragma=============================================================================

@implementation SelDeliveryDistanceView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self) {
        self.hidden = YES;
        [self setBackgroundColor:[UIColor clearColor]];
        [self drawCornerRadius];
        
        _distanceList = [[NSMutableArray alloc] initWithCapacity:5];
        
        _backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [_backImage setImage:[UIImage imageNamed:@"dropbox_bg.png"]];
        _backImage.userInteractionEnabled = YES;
        [_backImage drawCornerRadius];
        [self addSubview:_backImage];
        
        _distanceTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, frame.size.width, frame.size.height-10)];
        [_distanceTable setBackgroundColor:[UIColor clearColor]];
        _distanceTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _distanceTable.bounces = NO;
        _distanceTable.delegate = self;
        _distanceTable.dataSource = self;
        [_distanceTable drawCornerRadius];
        [_backImage addSubview:_distanceTable];
    }
    
    return self;
}

- (void)showOrVisible
{
    [self.distanceTable reloadData];
    [self.distanceTable autoHeight];
    [self.backImage autoHeight];

    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.hidden = !self.hidden;
        self.top = !self.hidden ? 0 : (0-self.distanceTable.height);
        
        [self autoHeight];
        if (self.height < 80) {
            self.height = 80;
            self.backImage.height = 80;
        }
    } completion:^(BOOL finished){

    }];
}

- (void)loadDataWithArray:(NSMutableArray *)distance
{
    _distanceList = distance;
    [_distanceTable reloadData];
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _distanceList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell123";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    NSDictionary *dic = [_distanceList objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [dic objectForKey:@"display"];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, tableView.frame.size.width, 1)];
    line.image = [UIImage imageNamed:@"dropbox_line.png"];
    
    [cell addSubview:line];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_delegate) {
        NSDictionary *dic = [_distanceList objectAtIndex:indexPath.row];
        [_delegate selectedDistanceFinished:dic];
    }
}

@end